//
//  ViewController.m
//  同步数据源
//
//  Created by 伍银荣 on 2020/7/5.
//  Copyright © 2020 com.example. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *copyedArr;
@property (nonatomic, strong) NSIndexPath *deleteIndex;

@end

@implementation ViewController

-(NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray arrayWithObjects:@"A",@"B",@"我是广告1",@"C",@"我是广告2",@"D",@"E", nil];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell_id";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.textLabel.text = self.dataArr[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataArr[indexPath.row] hasPrefix:@"我是广告"]) {
        return 80;
    }
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataArr[indexPath.row] hasPrefix:@"我是广告"]) {
        //处理因网络请求较慢,但是快速点击两行cell导致的数组数据无法正常更新,所以只能等上一行cell点击后数组更新后才能点击下一行cell
        if (self.deleteIndex != nil) {
            NSLog(@"请求正在处理中,请勿操作..");
            return;
        }
        //先数据拷贝
        self.copyedArr = [self.dataArr mutableCopy];
        NSLog(@"----%@",self.copyedArr.class);
        //记录删除操作
        self.deleteIndex = indexPath;
        //开启子线程
        [self loadMore];
        //先做删除操作
        [self.dataArr removeObjectAtIndex:indexPath.row];
        NSLog(@"1---dataArr = %@",self.dataArr);
        
        [self.tableView reloadData];
    }
}

- (void)loadMore {
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [queue addOperationWithBlock:^{
        //模拟耗时操作
        NSLog(@"---子线程---");
        sleep(2);
        [self.copyedArr removeObjectAtIndex:self.deleteIndex.row];
        NSLog(@"3---copyedArr = %@",self.copyedArr);
        NSArray *addArr = @[@"H",@"我是广告3",@"K",@"我是广告4",@"我是广告5"];
        [self.copyedArr addObjectsFromArray:addArr];
        NSLog(@"4----copyedArr = %@",self.copyedArr);
        [self.dataArr removeAllObjects];
        [self.dataArr addObjectsFromArray:self.copyedArr];
        [self.copyedArr removeAllObjects];
        self.deleteIndex = nil;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self.tableView reloadData];
        }];
    }];
}


@end
